package com.pz.dx.dxm.service.impl;

import cn.dev33.satoken.stp.StpUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.pz.dx.common.exception.BizCodeEnum;
import com.pz.dx.common.exception.RRException;
import com.pz.dx.dxm.config.saToken.SaTokenConstants;
import com.pz.dx.dxm.controller.vo.LoginRes;
import com.pz.dx.dxm.entity.UserEntity;
import com.pz.dx.dxm.service.LoginService;
import com.pz.dx.dxm.service.UserService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;


@Service("loginService")
public class LoginServiceImpl implements LoginService {
    @Autowired
    private UserService userService;

    @Override
    public LoginRes loginWithPwd(String email, String password) {
        QueryWrapper<UserEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("email", email);
        UserEntity one = userService.getOne(queryWrapper);
        if (one == null) {
            throw new RRException(BizCodeEnum.USER_NOT_EXIST, email);
        }

        BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
        if(passwordEncoder.matches(password, one.getPassword())) {
            StpUtil.login(one.getUserId());
            // 密码正确
            LoginRes.UserSession userSession = new LoginRes.UserSession();
            BeanUtils.copyProperties(one, userSession);

            // 创建userSession, 存放用户的基本信息
            StpUtil.getSession().set(SaTokenConstants.USER_SESSION_KEY, userSession);
            String token = StpUtil.getTokenValue();

            return new LoginRes(true, token, userSession);
        } else {
            throw new RRException(BizCodeEnum.USER_ERROR_PWD);
        }
    }
}
